package question.solution16;

import question.SolutionTemplate;

import java.util.Arrays;

public class Solution16 implements SolutionTemplate {

    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int closestSum = nums[0]+nums[1]+nums[nums.length-1];
        for(int i=1;i<nums.length-1;i++){
            int pa = i;
            int pb = 0;
            int pc = nums.length-1;
            while(pb < pc){
                int currentSum = nums[pa]+nums[pb]+nums[pc];
                if(currentSum == target){
                    return target;
                }
                if(Math.abs(currentSum - target) < Math.abs(closestSum - target)){
                    closestSum = currentSum;
                }
                if(currentSum < target){
                    do{
                        pb++;
                    }while(pb == pa);
                }else if(currentSum > target){
                    do{
                        pc--;
                    }while(pc == pa);
                }
            }
        }
        return closestSum;
    }

    @Override
    public void test() {
        int[] arr = {-1,2,1,-4};
        System.out.println(threeSumClosest(arr, 1));
//        System.out.println(myAtoi("-91283472332"));
    }

}
